import { Injectable } from '@nestjs/common'
import { Prisma } from '@prisma/client'
import { PrismaService } from 'nestjs-prisma'
import { DomainModel } from '../model'

@Injectable()
export class MetaResourceChartExampleDao {
  get table() {
    return this.prismaService.metaResourceChartExample
  }

  constructor(private readonly prismaService: PrismaService) {}

  /**
   * 数据列表
   * @param data
   * @returns
   */
  list(data: Prisma.MetaResourceChartExampleWhereInput): Promise<DomainModel.MetaResourceChartExample[]> {
    return this.table.findMany({
      where: data,
      orderBy: [
        {
          sortNo: 'desc',
        },
        {
          createTime: 'desc',
        },
      ],
    })
  }

  /**
   * 分组列表
   * @returns
   */
  listGroup(): Promise<string[]> {
    return this.table
      .findMany({
        distinct: ['groupLabel'],
        select: {
          groupLabel: true,
        },
      })
      .then(data => data.map(item => item.groupLabel))
  }

  /**
   * 标签是否存在，平台-项目-分组下的标签名称唯一
   * @param data
   * @returns
   */
  isLabelExists(
    data: Array<{
      label: string
      groupLabel: string
      id?: number
    }>
  ): Promise<boolean> {
    return this.prismaService
      .$transaction(
        data.map(row =>
          this.table.count({
            where: {
              groupLabel: row.groupLabel,
              label: row.label,
              id: {
                not: row.id,
              },
            },
          })
        )
      )
      .then(result => result.some(count => count > 0))
  }

  /**
   * 保存数据
   * @param data
   * @returns
   */
  save(data: Prisma.MetaResourceChartExampleCreateInput): Promise<DomainModel.MetaResourceChartExample> {
    return this.table.create({ data })
  }

  /**
   * 根据ID获取数据
   * @param id
   * @returns
   */
  getById(id: number): Promise<DomainModel.MetaResourceChartExample | null> {
    return this.table.findUnique({ where: { id } })
  }

  /**
   * 根据ID更新数据
   * @param id
   * @param data
   * @returns
   */
  updateById(
    id: number,
    data: Prisma.MetaResourceChartExampleUpdateInput
  ): Promise<DomainModel.MetaResourceChartExample> {
    return this.table.update({ data, where: { id } })
  }

  /**
   * 根据ID删除数据
   * @param id
   * @returns
   */
  deleteById(id: number): Promise<DomainModel.MetaResourceChartExample> {
    return this.table.delete({ where: { id } })
  }
}
